package controllers;

import play.libs.OpenID;
import play.mvc.Before;
import play.mvc.Controller;

/**
 * Created by IntelliJ IDEA.
 * User: bicho
 * Date: 21/01/12
 * Time: 8:47
 * To change this template use File | Settings | File Templates.
 */
public class OpenIdAuthentication extends Controller {
    @Before(unless = {"login", "authenticate"})
    static void checkAuthenticated() {
        if (!session.contains("user")) {
            login();
        }
    }

    public static void login() {
        render();
    }

    public static void authenticate(String user) {
        if (OpenID.isAuthenticationResponse()) {
            OpenID.UserInfo verifiedUser = OpenID.getVerifiedID();
            if (verifiedUser == null) {
                flash.error("Oops. Authentication has failed");
                login();
            }
            session.put("user", verifiedUser.id);
            index();
        } else {
            if (!OpenID.id(user).required("email", "http://axschema.org/contact/email").
                    required("firstname", "http://axschema.org/namePerson/first").
                    required("lastname", "http://axschema.org/namePerson/last").
                    required("country", "http://axschema.org/contact/country/home").
                    verify()) { // will redirect the user
                flash.error("Cannot verify your OpenID");
                login();
            }
        }
    }

    public static void index() {
        String user = session.get("user");
        render(user);
    }

}
